/**
 * 
 */
package com.qdairlines.common;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qdairlines.constant.BaseConsts;


/**
 * @author pangyannan
 * @date 2016年8月2日
 * @company QingDao Airlines
 * @description 主要是将数据转换为multiselect需要的数据格式
 */
public class MultiselectUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(MultiselectUtil.class);
	
	/**
	 * 将list 转换为 multiselect 所需要的josn格式, 需要传入list种的类要换换的 id 以及 name
	 * @param list
	 * @param valueName
	 * @param lableName
	 * @return
	 */
	public static <T> String  toJosn(List<T> list,String defaultVal,String valueName,String lableName,String language){
		if(list !=null && list.size()>0){
			 StringBuffer sb = new StringBuffer();
			 sb.append("[");
			 if(defaultVal ==null || "".equals(defaultVal)){
				 //如果没有有默认值，则添加 “请选择”
				 if(BaseConsts.EN_US.equals(language)){
					 sb.append("{value:\"\" , label:\"--please choose--\" },");
				 }else{
					 sb.append("{value:\"\" , label:\"--请选择--\" },");
				 }
			 }
			 for(T t: list){
				 try {
					 sb.append("{value:\"");
					 sb.append(BeanUtils.getProperty(t,valueName).toString());
					 sb.append("\",label:\"");
					 sb.append(BeanUtils.getProperty(t,lableName).toString());
					 sb.append("\"},");
				} catch (IllegalAccessException | InvocationTargetException
						| NoSuchMethodException e) {
					TraceUtil.error(logger, e);
				}
			 }
			String str =  sb.toString();
			str = StringUtils.substring(str, 0, str.length()-1);
			str = str +"]";
			return str;
		}
		return null;
	}

}
